//============================================================================
// Name        : lab4_2.cpp
// Author      : Binda&Aeolus
// Version     :
// Copyright   : Copyright 2011 Binda&Aeolus; All Rights Reserved
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <map>
#include<fstream>
#include <FileProcessor.cpp>
#include "Huffman.h"
#include <malloc.h>
using namespace std;

int main() {

	FileProcessor fp;
	vector<char> data;
	const string infile_name = "input.txt";
	const string outfile_name = "output.txt";
	map<char, int> char_count;
	int *w;
	HuffmanCode hc;
	HuffmanTree ht;
	fp.analyze(infile_name, char_count);
	map<char, int>::iterator map_it = char_count.begin();

	//初始化权值数组
	w = (int*) malloc(char_count.size() * sizeof(int));
	int k = 0;
	while (map_it != char_count.end()) {
		cout << map_it->first << ":" << map_it->second << endl;
		w[k] = map_it->second;
		++k;
		++map_it;
	}

	//cout << char_count.size() << endl;
	//求哈夫曼编码 ,存储在 hc
	HuffmanCoding(ht, hc, w, char_count.size());

	//映射表
	map<char, int> code_table;
	k = 1;
	map_it = char_count.begin();
	while (map_it != char_count.end()) {
		code_table.insert(make_pair(map_it->first, k));
		k++;
		map_it++;
	}



    //以下为文件编码
	ifstream in;
	in.open(infile_name.c_str());
	ofstream out;
	out.open(outfile_name.c_str());
	if (in) {
		char c;
		while (in>>c) {
			string temp(hc[code_table[c]]);
			out << temp;
		}
	} else
		cout << "fail!" << endl;


	//输出编码规则
	 out.close();
	 out.clear();
	   out.open("rule.txt");
		cout<<"Encode Rule:"<<endl;
	   map_it=code_table.begin();
	   while(map_it!=code_table.end())
	   {
	      string tem(hc[map_it->second]);
	      cout<<map_it->first<<":"<<tem;
	      out<<map_it->first<<":"<<tem;
	      out<<endl;
	      cout<<endl;
	      map_it++;
	   }
	/*for(int i=1;i<=char_count.size();i++)
	 {
	 int j=0;
	 while(hc[i][j]!='\0')
	 {
	 //out<<hc[i][j];
	 printf("%c",hc[i][j]);
	 j++;
	 }
	 //out<<endl;
	 printf("\n");

	 }*/
    out.close();
    in.close();
	return 0;
}
